import requests
from datetime import datetime,timedelta
import threading
import re
import asyncio
import aiohttp

total_res = [""] * 10
lock = threading.Lock() #用锁来保护临界资源res

# 日措施动态
def category_1(cookie: str):
    global total_res
    try:
        nowDate = datetime.now()
        rq = nowDate.strftime("%Y-%m-%d")
        url = f"http://10.84.4.74/yyqer/cqgc/dhc/cstj_json.jsp?srq={rq}"
        response = requests.get(url, headers={"cookie": cookie},timeout=15)

        data1 = response.json()["res"]
        res = f"今日措施动态数据(不含复兴)如下："
        res = res + "|措施|井数(口)|\n"
        res = res + "|---" * 2 + "|\n"
        for x in data1:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x) + "|\n"

        data2 = response.json()["res1"]
        res = res + f"今日措施动态数据(复兴)如下："
        res = res + "|措施|井数(口)|\n"
        res = res + "|---" * 2 + "|\n"
        for x in data2:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x) + "|\n"

        data3 = response.json()["res2"]
        res = res + f"今日药剂用量动态数据如下："
        res = res + "|药剂|井数(口)|药剂用量|\n"
        res = res + "|---" * 3 + "|\n"
        for x in data3:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x) + "|\n"
        with lock:
            total_res += res[:3000] + "\n\n"
    except Exception as e:
        with lock:
            total_res += "日措施动态无法获取数据\n\n"

#泡排井跟踪
def category_2(cookie: str):
    global total_res
    try:
        nowDate = datetime.now()
        rq = nowDate.strftime("%Y-%m-%d")
        url = f"http://10.84.4.74/yyqer/scbb/csyb/ppjrdhz_json.jsp?rq=2025-04-20"
        response = requests.get(url, headers={"cookie": cookie},timeout=15)

        data = response.json()["rs"]

        res = f"泡排井跟踪数据如下："
        res = res + "|井号|起泡剂Kg|消泡剂Kg|起泡剂配液浓度%|起泡剂加注时间h|起泡排量L/h|\n"
        res = res + "|---" * 6 + "|\n"
        for x in data:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + x[3] + "|" + "|".join(x[11:-1]) + "|\n"
        with lock:
            total_res += res[:3000] + "\n\n"
    except Exception as e:
        with lock:
            total_res += "泡排井跟踪无法获取数据\n\n"

#循环气举井跟踪
def category_3(cookie: str):
    global total_res
    try:
        nowDate = datetime.now()
        preDate = nowDate - timedelta(days=90)
        erq = nowDate.strftime("%Y-%m-%d")
        srq = preDate.strftime("%Y-%m-%d")
        url = f"http://10.84.4.74/yyqer/cqgygl/csgl/xhqj_ptzl_json.jsp?srq={srq}&erq={erq}"
        response = requests.get(url, headers={"cookie": cookie},timeout=15)

        data = response.json()["res"]

        res = f"循环气举井跟踪数据如下："
        res = res + "|集气站|循环气举井产气量(m³/d)|循环气举井产水量(m/d)|循环气举井数|平台总气量(m³/d)|平台总水量(m³/d)|平台总井数|注入气量(m³/d)|产出：注入|气举时长(h)|助推时长(h)|助推水量(m³)|放空时长(h)|放空气量(m³)|放空水量(m³)|是否在运行|\n"
        res = res + "|---" * 16 + "|\n"
        for x in data:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x) + "|\n"
        with lock:
            total_res += res[:3000] + "\n\n"
    except Exception as e:
        with lock:
            total_res += "循环气举井跟踪无法获取数据\n\n"

#油管完井管柱数据
def category_4(cookie: str,jh: str):
    global total_res
    try:
        url = f"http://10.84.4.74/yyqer/cqgc/jczl/wjgz_tj_ygwj4_json.jsp?ffilter=a.JH&filter={jh}"
        response = requests.get(url, headers={"cookie": cookie},timeout=15)

        data = response.json()["rs5"]

        res = f"{jh}的油管完井管柱数据如下："
        res = res + "|井号|油管内径(mm)|油管外径(mm)|油管壁厚(mm)|油管钢级|油管扣型|完井管柱结构|完井管柱下入深度(m)|完井管柱底部位置(井斜角)|开工日期|完工日期|施工周期(d)|施工单位|油管生产厂家|下管作业方式|投产日期|投产与下油管间隔天数|下管前一天套压|下管前一天日产气量(方)|备注|\n"
        res = res + "|---" * 20 + "|\n"
        for x in data:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x) + "|\n"
        with lock:
            total_res += res[:3000] + "\n\n"
    except Exception as e:
        with lock:
            total_res += "油管完井管柱数据无法获取数据\n\n"

#检管
def category_5(cookie: str):
    global total_res
    try:
        nowDate = datetime.now()
        preDate = nowDate - timedelta(days=90)
        erq = nowDate.strftime("%Y-%m-%d")
        srq = preDate.strftime("%Y-%m-%d")
        url = f"http://10.84.4.74/yyqer/cqgc/cszy/jqgx_jgzy_json.jsp?srq={srq}&erq={erq}"
        response = requests.get(url, headers={"cookie": cookie},timeout=15)

        data = response.json()["res"]
        sortData = sorted(data, key=lambda x: x[1], reverse=True)
        res = f"检管数据如下："
        res = res + "|井号|检管时间|压井液量(方)|检管后日均产气(方)|检管后日均产水(方)|检管后累产气(方)|检管后累产水(方)|区间产气(方)|区间产水(方)|\n"
        res = res + "|---" * 9 + "|\n"
        for x in sortData:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x) + "|\n"
        with lock:
            total_res += res[:3000] + "\n\n"
    except Exception as e:
        with lock:
            total_res += "检管无法获取数据\n\n"

#气举统计
import traceback
async def category_6(cookie: str,jh: str):
    startTime = datetime.now()
    global total_res
    try:
        async with aiohttp.ClientSession() as session:
            nowDate = datetime.now()
            preDate = nowDate - timedelta(days=90)
            erq = nowDate.strftime("%Y-%m-%d")
            srq = preDate.strftime("%Y-%m-%d")
            url = f"http://10.84.4.74/yyqer/cqgc/cszy/cq_zsqj_json.jsp?jhs={jh}&rq={erq}&rq1={srq}&cslx=气举"
            header = {"cookie": cookie}
            async with session.get(url,timeout=15,headers=header) as response:
                data = await response.json()
                data = data["list"][0]

                res = f"{jh}的气举统计如下："
                res = res + "|井号|区块|管理区|施工开始时间|施工结束时间|气举天数|措施开始时间|措施截止时间|AB靶点垂深差|平均水气比|气举前油压|气举前套压|措施有效天数|措施前一周日均产气(万方)|措施后一周日均产气(万方)|措施前一周生产时率(%)|措施后一周生产时率(%)|措施阶段累产气(万方)|\n"
                res = res + "|---" * 18 + "|\n"
                for x in data:
                    for i in range(0, len(x)):
                        x[i] = "无" if x[i] == "" else x[i]
                    res = res + "|" + "|".join(x) + "|\n"
                total_res[5] = res[:3000] + "\n\n"
                endTime = datetime.now()
                print(f"等待了：{endTime - startTime}")
    except Exception as e:
        print(f"{traceback.format_exc()}")
        total_res[5] = f"气举统计无法获取数据{e}\n\n"
        endTime = datetime.now()
        print(f"等待了：{endTime - startTime}")

#泡排统计
async def category_7(cookie: str):
    startTime = datetime.now()
    global total_res
    try:
        async with aiohttp.ClientSession() as session:
            nowDate = datetime.now()
            rq = nowDate.strftime("%Y-%m-%d")
            url = f"http://10.84.4.74/yyqer/cqgc/cszy/cq_zs_json.jsp?rq={rq}&cslx=泡排"
            header = {"cookie": cookie}
            async with session.get(url,timeout=15,headers=header) as response:
                data = await response.json()
                data = data["list"][0]
                sortData = sorted(data, key=lambda x: x[3], reverse=True)
                res = f"泡排统计如下："
                res = res + "|井号|区块|管理区|措施开始时间|措施截止时间|AB靶点垂深差|平均水气比|是否运行|停运原因|当日产气量(方)|前一日产气量(方)|产量对比(方)|月生产时率(%)|措施有效天数|措施前日均产气(万方)|措施后日均产气(万方)|措施前平均生产时率(%)|措施后平均生产时率(%)|措施前平均油套压差(MPa)|措施后平均油套压差(MPa)|措施阶段平均日产气(万方)|措施阶段累产气(万方)|措施阶段增产气量(万方)|\n"
                res = res + "|---" * 23 + "|\n"
                for x in sortData:
                    for i in range(0, len(x)):
                        x[i] = "无" if x[i] == "" else x[i]
                    res = res + "|" + "|".join(x[:-1]) + "|\n"
                total_res[6] = res[:3000] + "\n\n"
                endTime = datetime.now()
                print(f"等待了：{endTime - startTime}")
    except Exception as e:
        total_res[6] = f"泡排统计无法获取数据{e}\n\n"
        endTime = datetime.now()
        print(f"等待了：{endTime - startTime}")

#柱塞统计
def category_8(cookie: str):
    startTime = datetime.now()
    global total_res
    try:
        nowDate = datetime.now()
        rq = nowDate.strftime("%Y-%m-%d")
        url = f"http://10.84.4.74/yyqer/cqgc/cszy/cq_zs_json.jsp?rq={rq}&cslx=柱塞"
        response = requests.get(url, headers={"cookie": cookie},timeout=15)

        data = response.json()["list"][0]
        sortData = sorted(data, key=lambda x: x[3], reverse=True)
        res = f"柱塞统计如下："
        res = res + "|井号|区块|管理区|措施开始时间|措施截止时间|AB靶点垂深差|平均水气比|卡定器下深m|开关井制度|油管尺寸|当日产气量(方)|前一日产气量(方)|产量对比(方)|月生产时率(%)|措施有效天数|措施前日均产气(万方)|措施后日均产气(万方)|措施前平均生产时率(%)|措施后平均生产时率(%)|措施前平均油套压差(MPa)|措施后平均油套压差(MPa)|措施阶段平均日产气(万方)|措施阶段累产气(万方)|措施阶段增产气量(万方)|\n"
        res = res + "|---" * 24 + "|\n"
        for x in sortData:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x[:-1]) + "|\n"
        total_res[7] = res[:3000] + "\n\n"
        endTime = datetime.now()
        print(f"等待了：{endTime - startTime}")
    except Exception as e:
        total_res[7] = "柱塞统计无法获取数据\n\n"
        endTime = datetime.now()
        print(f"等待了：{endTime - startTime}")

#智能间开统计
def category_9(cookie: str):
    global total_res
    try:
        nowDate = datetime.now()
        rq = nowDate.strftime("%Y-%m-%d")
        url = f"http://10.84.4.74/yyqer/cqgc/cszy/cq_zs_json.jsp?rq={rq}&cslx=智能间开"
        response = requests.get(url, headers={"cookie": cookie},timeout=15)

        data = response.json()["list"][0]
        sortData = sorted(data, key=lambda x: x[3], reverse=True)
        res = f"智能间开统计如下："
        res = res + "|井号|区块|管理区|措施开始时间|措施截止时间|AB靶点垂深差|平均水气比|-|当日产气量(方)|前一日产气量(方)|产量对比(方)|月生产时率(%)|措施有效天数|措施前日均产气(万方)|措施后日均产气(万方)|措施前平均生产时率(%)|措施后平均生产时率(%)|措施前平均油套压差(MPa)|措施后平均油套压差(MPa)|措施阶段平均日产气(万方)|措施阶段累产气(万方)|措施阶段增产气量(万方)|\n"
        res = res + "|---" * 22 + "|\n"
        for x in sortData:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x[:-1]) + "|\n"
        with lock:
            total_res += res[:3000] + "\n\n"
    except Exception as e:
        with lock:
            total_res += "智能间开统计无法获取数据\n\n"

#管网气气举统计
def category_10(cookie: str):
    global total_res
    try:
        nowDate = datetime.now()
        rq = nowDate.strftime("%Y-%m-%d")
        url = f"http://10.84.4.74/yyqer/cqgc/cszy/cq_zs_json.jsp?rq={rq}&cslx=管网气气举"
        response = requests.get(url, headers={"cookie": cookie},timeout=15)

        data = response.json()["list"][0]
        sortData = sorted(data, key=lambda x: x[3], reverse=True)
        res = f"管网气气举统计如下："
        res = res + "c\n"
        res = res + "|---" * 22 + "|\n"
        for x in sortData:
            for i in range(0, len(x)):
                x[i] = "无" if x[i] == "" else x[i]
            res = res + "|" + "|".join(x[:-1]) + "|\n"
        with lock:
            total_res += res[:3000] + "\n\n"
    except Exception as e:
        with lock:
            total_res += "管网气气举统计无法获取数据\n\n"

# def category_(cookie: str):
#     global total_res
#     try:
#         with lock:
#             total_res += res[:3000] + "\n\n"
#     except Exception as e:
#         with lock:
#             total_res += "无法获取数据\n\n"

async def main(choice: str, cookie: str, jh: str):
    choice = re.findall(r'\d+', choice) #分割
    choice = list(set(choice)) #去重,
    print(choice)

    task1 = asyncio.create_task(category_6(cookie,jh))
    task2 = asyncio.create_task(category_7(cookie))
    tasks =[task1, task2]
    await asyncio.gather(*tasks)

    return{
        "result": total_res,
    }

startTime = datetime.now()
res = asyncio.run(main("6,7","userName=wlx2023.jhyt; password=; JSESSIONID=FAF4E4DAEC1C63B0243BD681A851A067",""))
print(res)
print(len(res["result"]))
endTime = datetime.now()
print(f"等待了：{endTime - startTime}")